package com.x.test;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.x.mapper.EmpMapper;
import com.x.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * ClassName: MyBatistest
 * Package: IntelliJ IDEA
 * Description: 分页插件PageHelper的使用
 * Written by HanXu
 * Create 2024.09.09 23:50
 */
public class MyBatistest {
    private SqlSession sqlSession;
    @BeforeEach
    public void init() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = sessionFactoryBuilder.build(inputStream);

        sqlSession = sessionFactory.openSession();
    }

    @AfterEach
    public void clear(){
        //开启事务自动提交
        //session = sessionFactory.openSession(true);

        //会话关闭
        sqlSession.close();
    }

    /**
     * 分页插件PageHelper的使用
     */

    @Test
    public void test_01(){
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);

        //使用分页插件设置分页数据
        PageHelper.startPage(2,3);//当前是第2页，每次显示3个

        List<Employee> employees = mapper.queryAll();

        //将查询数据封装到PageInfo的分页实体类(可以获取一共多少页，一共多少条)
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);

        //获取当前分页的数据集合
        List<Employee> list = pageInfo.getList();//当前页的实体类(员工)的集合
        //获取总页数
        int pages = pageInfo.getPages();
        //获取总条数
        long total = pageInfo.getTotal();
        //......

        System.out.println("******************************************");
        System.out.println("总页数: "+pages);
        System.out.println("总条数: "+total);
        System.out.println("当前分页数据集合: "+list);

    }
}
